﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.Entity.SiteLibraryManage;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Domain.IRepository.SiteLibraryManage;
using YunSpace.Domain.ViewModel.MiniSite;
using YunSpace.Domain.ViewModel.SiteLibraryManage;
using YunSpace.Domain.ViewModel.WeChat;
using YunSpace.Repository.SiteLibraryManage;
#endregion

namespace YunSpace.Application.SiteLibraryManage
{
    public class SpaceApp
    {
        private ISpaceRepository service = new SpaceRepository();
        private PhotosApp photosApp = new PhotosApp();
        private MarketApp marketApp = new MarketApp();
        private PriceApp priceApp = new PriceApp();

        public List<SpaceEntity> GetList(string keyword = "")
        {
            var expression = ExtLinq.True<SpaceEntity>();
            return service.IQueryable(expression).OrderBy(t => t.F_Id).ToList();
        }
        public List<SpaceEntity> GetList(Pagination pagination, string queryJson, string uid)
        {
            var result = new List<SpaceEntity>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select distinct si.* from SL_Space  si left join  SL_Site sp 
                             on (sp.F_Id = si.F_SiteId) 
                             where 1=1 and F_SupplierId=@uid {0}{1}";
                var countSql = @"select Count(1) from (select distinct si.* from SL_Space  si left join  SL_Site sp 
                             on (sp.F_Id = si.F_SiteId) where 1=1 and F_SupplierId=@uid {0}{1}) as t";

                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
               {
                    new MySqlParameter("@uid",uid)
                };
                string keyWhere = "";
                if (!queryParam["keyword"].IsEmpty())
                {
                    string keyword = queryParam["keyword"].ToString();                    
                    keyWhere = " AND si.title like'%" + keyword + "%'";
                }
                string siteWhere = "";
                if (!queryParam["F_SiteId"].IsEmpty())
                {
                    string F_SiteId = queryParam["F_SiteId"].ToString();                    
                    siteWhere = " AND si.F_SiteId="+F_SiteId;
                }
                var sql=String.Format(strSql, keyWhere, siteWhere);
                var csql = String.Format(countSql, keyWhere, siteWhere);
                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;

                //strSql = string.Format("{0} ORDER BY si.{1}", strSql, pagination.sidx);

                strSql = string.Format("{0} order by si.F_LastModifyTime desc LIMIT {1},{2};", sql, startNo, endNo);

                int count = service.Count(csql, parameter);
                pagination.records = count;
                result = db.FindList<SpaceEntity>(sql, parameter);
            }
            return result;
        }
        public List<SpaceListEntity> GetSpaceList(Pagination pagination, string queryJson)
        {
            using (var db = new RepositoryBase())
            {
                string strSql = @"select sp.* from SL_Space sp  where 1=1 {0}{1} ";

                var queryParam = queryJson.ToJObject();
                strSql = string.Format(strSql, queryParam["keyword"].IsEmpty() ? "" : " AND sp.title LIKE'%" + queryParam["keyword"] + "%'",
                           queryParam["F_SiteId"].IsEmpty() ? "" : " and sp.F_SiteId =@F_SiteId ");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_SiteId", queryParam["F_SiteId"])
                };
                return db.FindList<SpaceListEntity>(strSql, parameter, pagination);
            }
        }
        public List<SpaceListEntity> GetListBySiteId(string F_SiteId)
        {
            using (var db = new RepositoryBase())
            {
                string sql = @"select title,F_Id,F_SiteId from SL_Space where F_SiteId=@F_SiteId limit 0,50";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@F_SiteId", F_SiteId)
                };
                return db.FindList<SpaceListEntity>(sql, parameter);
            }
        }

        public SpaceEntity GetForm_Mini(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public SpaceActionManage GetForm(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                SpaceActionManage data = new SpaceActionManage();
                string strSql1 = @"select * from SL_Space where F_Id='" + keyValue + "';";
                string strSql2 = @"select * from Space_Market_Attrs where F_SpaceId='" + keyValue + "';";
                //string strSql7 = @"select * from Site_Price where F_SpaceId='" + keyValue + "';";
                string strSql3 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='SpaceFiles' and F_DeleteMark=0;";
                string strSql4 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='Space' and F_DeleteMark=0;";
                string strSql5 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='SpacePlaneFile' and F_DeleteMark=0;";
                string strSql6 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='SpaceVideo' and F_DeleteMark=0;";

                var data1 = db.FindList<SpaceEntity>(strSql1);
                var data2 = db.FindList<MarketEntity>(strSql2);
                var data3 = db.FindList<PhotosEntity>(strSql3);
                var data4 = db.FindList<PhotosEntity>(strSql4);
                var data5 = db.FindList<PhotosEntity>(strSql5);
                var data6 = db.FindList<PhotosEntity>(strSql6);
                //var data7 = db.FindList<PriceEntity>(strSql7);
                data.spaceEntity = data1.FirstOrDefault();
                data.marketEntity = data2.FirstOrDefault();
                data.FilesList = data3;
                data.PhotosList = data4;
                data.PlanePhotosList = data5;
                data.VideoList = data6;
                //data.priceEntity = data7.FirstOrDefault();
                return data;
            }

            //return service.FindEntity(keyValue);
        }

        #region  场地大师APP接口SubmitSpaceForm
        public string SubmitSpaceForm(SpaceEntity spaceEntity, string keyValue, List<PhotosEntity> imgList)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    spaceEntity.Modify(keyValue);
                    service.Update(spaceEntity);
                }
                else
                {
                    spaceEntity.Create();
                    spaceEntity.F_LastModifyTime = spaceEntity.F_CreatorTime;
                    spaceEntity.F_LastModifyUserId = spaceEntity.F_CreatorUserId;
                    service.Insert(spaceEntity);
                }
                if (imgList.Count > 0)
                {
                    db.Delete<PhotosEntity>(p => p.photoable_id == spaceEntity.F_Id && p.photoable_type == "Space");

                    imgList.ForEach(item =>
                    {
                        item.F_CreatorUserId = spaceEntity.F_CreatorUserId;
                        item.photoable_id = spaceEntity.F_Id;
                        item.Create();
                        db.Insert<PhotosEntity>(item);
                    });
                }
                db.Commit();
            }
            return spaceEntity.F_Id;
        }

        /// <summary>
        /// 用户空间列表(获取最后的10条数)
        /// </summary>
        public List<SiteMgrSpaceActionModel> GetSpaces(string lastId, int count, string F_SiteId, string F_Id, int state)
        {
            // 最新创建的 10 条数据 小场地类型为 F_Category = 1
            //return service.GetSites(lastId, count);

            using (var db = new RepositoryBase())
            {
                var result = new List<SiteMgrSpaceActionModel>();

                var strSql = @"SELECT sp.F_Id,sp.title,sp.market_price,sp.units,sp.through_three_areas,sp.max_seating_capacity,
                                sp.area,sp.height,sp.introduced,sp.state,sp.inner_price,sp.accept_weight,sp.limit_height,
                                sp.length_width,sp.current_floor,sp.power_supply,sp.network,sp.vehicle,sp.price_build,sp.remark,
                                sp.price_market_build,sp.exit_limit,sp.F_CreatorUserId,sp.F_SiteId from SL_Space sp
                                WHERE 1=1 {0}{2}{3}{4}  GROUP BY sp.f_id ORDER BY sp.F_CreatorTime DESC
                                LIMIT 0, {1};";

                if (!F_Id.IsNullOrEmpty())
                {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND sp.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@lastId)", count,
                        " and sp.F_SiteId=@F_SiteId", " and sp.F_Id=@F_id", state >= 0 ? " and sp.state=@state" : "");
                }
                else
                {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND sp.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@lastId)", count,
                        " and sp.F_SiteId=@F_SiteId", "", state >= 0 ? " and sp.state=@state" : "");
                }
                DbParameter[] parameter =
                    {
                        new MySqlParameter("@state", state),
                        new MySqlParameter("@lastId", lastId),
                        new MySqlParameter("@F_SiteId", F_SiteId),
                        new MySqlParameter("@F_id",F_Id)
                    };
                result = db.FindList<SiteMgrSpaceActionModel>(strSql, parameter);
                return result;
            }
        }

        #endregion

        #region 嗨空间APP接口

        /// <summary>
        /// 根据人数范围来获取相关场地
        /// </summary>
        /// <param name="min">最少人数</param>
        /// <param name="max">最大人数</param>
        public int GetSiteNumByPeopleNum(int min, int max)
        {
            var strSql = @"select count(1) from (select ss.F_SiteId from SL_Space ss where ss.max_seating_capacity >= @min and ss.max_seating_capacity <= @max and ss.F_SiteId  is not null
                            group by ss.F_SiteId) a inner join SL_Site ssite on a.F_SiteId = ssite.F_Id where ssite.F_Category = 1";
            DbParameter[] parameter =
                    {
                        new MySqlParameter("@min", min),
                        new MySqlParameter("@max",max)
                    };

            return service.Count(strSql, parameter);
        }

        #endregion


        #region


        /// <summary>
        /// 获取小程序空间及空间图片信息
        /// </summary>
        /// <returns></returns>
        public List<WeCharSpaceModel> Get_SpaceFrom(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                List<WeCharSpaceModel> spaceList = new List<WeCharSpaceModel>();
                var strSql = @"select s.F_Id,s.title,s.f_siteid,s.through_three_areas,s.max_seating_capacity,s.area,s.height,s.limit_height,s.current_floor,
                            s.vehicle,s.F_MarketPrice,s.accept_weight,F_Facilities,F_Units,introduced,p.F_path as f_PhotoUrl 
                            from SL_Space s inner join SL_Photos p on s.F_Id=p.photoable_id and p.photoable_type='space' and is_cover=1
                            where s.f_siteid=@fId and state=1  group by s.F_Id";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue)
                };
                spaceList = db.FindList<WeCharSpaceModel>(strSql, parameter);
                for (var i = 0; i < spaceList.Count; i++)
                {
                    //获取每个空间图片
                    var photoSql = @"select * from SL_Photos p where p.photoable_id='" + spaceList[i].F_Id + "' and p.photoable_type='space' and p.F_DeleteMark!=1 order by is_cover,F_CreatorTime desc";
                    spaceList[i].SpacePhotos = db.FindList<PhotosEntity>(photoSql);
                    //获取每个空间评价数据
                    var commentSql = @"select sum(F_SiteLike)likeCounts,F_SpaceId as F_Id,format(sum(F_SiteLike)/count(F_SpaceId),0) star from WeChat_Comment wc where wc.F_SpaceId='" + spaceList[i].F_Id + "'  group by wc.F_SpaceId ";
                    spaceList[i].SpaceComment = db.FindList<WeCharCommentModel>(commentSql).FirstOrDefault();
                }
                return spaceList;
            }
        }
        #endregion

        /// <summary>
        /// 判断空间是否有相关的档期
        /// </summary>
        /// <param name="spaceId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public bool IsSpaceFull(string spaceId, DateTime? startDate, DateTime? endDate)
        {
            if (!spaceId.IsNullOrEmpty() && startDate.HasValue && endDate.HasValue)
            {
                using (var db = new RepositoryBase())
                {
                    var strSql = @"select 1 from MiniSite_ScheduleRecord ms where ms.F_SpaceId=@spaceid and ms.F_Date between DATE_FORMAT('@startDate','%m-%d-%Y') and DATE_FORMAT('@endDate','%m-%d-%Y')";
                    DbParameter[] parameter =
                    {
                    new MySqlParameter("@spaceid", spaceId),
                    new MySqlParameter("@startDate", startDate.Value),
                    new MySqlParameter("@endDate", endDate.Value)
                };
                    return db.Count(strSql, parameter) == 1;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取小场地APP信息
        /// </summary>
        /// <returns></returns>
        public List<SpaceActionModel> GetSpaceFrom(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select s.F_Id,s.title,s.f_siteid,( select path from SL_Photos p 
                             where s.F_Id=p.photoable_id and p.photoable_type='space' order by is_cover,F_CreatorTime desc limit 1) as f_PhotoUrl  from SL_Space s 
                            where s.f_siteid=@fId and state=1";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue)
                };
                return db.FindList<SpaceActionModel>(strSql, parameter);
            }
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(SpaceEntity spaceEntity, List<PhotosEntity> imgList, MarketEntity marketEntity, string keyValue)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    spaceEntity.Modify(keyValue);
                    service.Update(spaceEntity);
                }
                else
                {
                    spaceEntity.Create();
                    spaceEntity.F_LastModifyUserId = spaceEntity.F_CreatorUserId;
                    spaceEntity.F_LastModifyTime = spaceEntity.F_CreatorTime;
                    service.Insert(spaceEntity);
                }
                //if (priceEntity != null) {
                //    priceEntity.F_SiteId = spaceEntity.F_SiteId;
                //    priceEntity.F_SpaceId = spaceEntity.F_Id;
                //    priceApp.SubmitForm(priceEntity, priceEntity.F_Id);
                //}
                if (imgList != null && imgList.Count > 0)
                {
                    photosApp.updatePhotoList(imgList, spaceEntity.F_Id);
                }
                if (!marketEntity.IsEmpty())
                {
                    marketEntity.F_SpaceId = spaceEntity.F_Id;
                    marketApp.SubmitForm(marketEntity, keyValue);
                }
                db.Commit();
            }
        }

        /// <summary>
        /// 根据供应商DI获取空间ID
        /// </summary>
        /// <returns></returns>
        public List<SiteMgrSpaceBySupplierIdActionModel> GetSpaceBySupplierId(string supplierId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT  site.F_Id F_SiteId, s.F_Id F_SpaceId ,s.title F_SpaceTitle, site.title F_SiteTitle, site.F_SupplierId   FROM  SL_Space  s INNER JOIN  SL_Site  site   ON s.F_SiteId = site.F_Id
                                WHERE site.F_SupplierId =@supplierId";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@supplierId", supplierId)
                };
                return db.FindList<SiteMgrSpaceBySupplierIdActionModel>(strSql, parameter);
            }
        }

        public List<PhotosEntity> GetPhoto(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                string strSql = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='Space' and F_DeleteMark=0;";
                var data = db.FindList<PhotosEntity>(strSql);
                return data;
            }
        }
    }
}

